package com.example.nacos.discovery;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;

import java.util.List;
import java.util.Properties;

/**
 * Nacos 服务发现示例
 * 
 * 依赖：
 * <dependency>
 *     <groupId>com.alibaba.nacos</groupId>
 *     <artifactId>nacos-client</artifactId>
 *     <version>2.3.0</version>
 * </dependency>
 */
public class NacosServiceDiscoveryExample {
    
    private static final String SERVER_ADDR = "localhost:8848";
    private static final String SERVICE_NAME = "example-service";
    
    public static void main(String[] args) throws NacosException, InterruptedException {
        // 1. 创建命名服务
        Properties properties = new Properties();
        properties.put("serverAddr", SERVER_ADDR);
        // 如果需要认证
        // properties.put("username", "nacos");
        // properties.put("password", "nacos");
        
        NamingService namingService = NacosFactory.createNamingService(properties);
        
        // 2. 注册服务实例
        Instance instance = new Instance();
        instance.setIp("127.0.0.1");
        instance.setPort(8080);
        instance.setWeight(1.0);
        instance.setHealthy(true);
        instance.setEnabled(true);
        instance.setEphemeral(true); // 临时实例
        
        namingService.registerInstance(SERVICE_NAME, instance);
        System.out.println("服务注册成功: " + SERVICE_NAME);
        
        // 3. 查询服务实例列表
        List<Instance> instances = namingService.getAllInstances(SERVICE_NAME);
        System.out.println("\n服务实例列表:");
        for (Instance inst : instances) {
            System.out.println("  - " + inst.getIp() + ":" + inst.getPort() + 
                             " (权重: " + inst.getWeight() + ", 健康: " + inst.isHealthy() + ")");
        }
        
        // 4. 选择一个健康实例（负载均衡）
        Instance selectedInstance = namingService.selectOneHealthyInstance(SERVICE_NAME);
        System.out.println("\n选择的实例: " + selectedInstance.getIp() + ":" + selectedInstance.getPort());
        
        // 5. 订阅服务变化
        namingService.subscribe(SERVICE_NAME, new EventListener() {
            @Override
            public void onEvent(Event event) {
                if (event instanceof NamingEvent) {
                    NamingEvent namingEvent = (NamingEvent) event;
                    System.out.println("\n服务实例变化:");
                    for (Instance inst : namingEvent.getInstances()) {
                        System.out.println("  - " + inst.getIp() + ":" + inst.getPort());
                    }
                }
            }
        });
        
        System.out.println("\n监听服务变化中... (按 Ctrl+C 退出)");
        
        // 模拟服务运行
        Thread.sleep(30000);
        
        // 6. 注销服务
        namingService.deregisterInstance(SERVICE_NAME, "127.0.0.1", 8080);
        System.out.println("\n服务注销成功");
    }
}

